<template>
  <main>
    <h1>登录页面</h1>

    <form id="payment-form" @submit.prevent="handleSubmit">
      <div>
        <input id="name">
      </div>
      
      <button 
        id="submit"
        :disabled="isLoading"
      >
        登录
      </button>
      <sr-messages :messages="messages" />
    </form>
    <div>
      <a href="/registry">没有账号去注册</a>
    </div>
  </main>
</template>
<script setup>
import { ref } from "vue";

import SrMessages from "./SrMessages.vue";

const isLoading = ref(false);
const messages = ref([]);



const handleSubmit = async () => {
  if (isLoading.value) {
    return;
  }

  isLoading.value = true;
  const nameInput = document.querySelector('#name');
  console.log(nameInput.value)
  await fetch(
      '/api/user/login',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: nameInput.value,
        }),
      }
    ).then((r) => {
      console.log('第一个then', r)
      return r.json()
    }).then((r) => {
      console.log('第二个then', r)
      if (r.code == 200) {
        sessionStorage.setItem('id', r.data.id)
        sessionStorage.setItem('name', r.data.name)
        sessionStorage.setItem('email', r.data.email)
        sessionStorage.setItem('stripeCustomerId', r.data.stripeCustomerId)
        window.location.href = '/'; 
      } else {
        messages.value.push('登录信息错误， 请重新登录');
      }
    });

  isLoading.value = false;
}
</script>